package com.qys.livesMall.kafka.config;


import com.qys.livesMall.kafka.annotation.AutoIncKey;
import com.qys.livesMall.kafka.entity.SeqInfo;
import jakarta.annotation.Resource;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

@Component
public class InsertEventListener extends AbstractMongoEventListener<Object> {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        Object source = event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);
                    /** 查询添加了自增注解的字段 */
                    if (field.isAnnotationPresent(AutoIncKey.class)) {
                        /** 更新该字段 */
                        field.set(source, getNextId(source.getClass().getSimpleName()));
                    }
                }
            });
        }
    }


    private Long getNextId(String collectionName) {
        Query query = new Query(Criteria.where("collectionName").is(collectionName));
        Update update = new Update();
        /** 主键递增1，设置为Long型 */
        update.inc("seqId", 1L);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        /** 原子操作，修改并返回 */
        SeqInfo seqInfo = mongoTemplate.findAndModify(query, update, options, SeqInfo.class);
        return seqInfo.getSeqId();
    }
}
